package com.yushixin.common.util;

import lombok.extern.slf4j.Slf4j;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * Bean工具类
 */
@Slf4j
public class BeanUtil {

    /**
     * Bean转Map
     */
    public static Map<String, Object> beanToMap(Object obj) {
        Map<String, Object> map = new HashMap<>();
        if ( Objects.nonNull(obj) ) {
            Class<?> clazz = obj.getClass();
            Field[] fields = clazz.getDeclaredFields();
            try {
                for (Field field : fields) {
                    field.setAccessible(true);
                    map.put(field.getName(), field.get(obj));
                }
            } catch (IllegalAccessException e) {
                log.error("Bean转Map异常", e);
            }
        }
        return map;
    }

    private BeanUtil() {}
}